package com.example.Cairodio;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
 * 
 * @author Monica
 * 
 *         The class that displays the welcome screen for the application
 *         connect to the server to synchronize with the local DB
 */
public class CairodioClient extends Activity {
	static final String TAG = "GNUC-TUTORIAL";
	static final String SERVER = "http://cairodio-app.appspot.com";

	double Version;
	String[] PlacesNames;
	double[] PlacesLat;
	double[] PlacesLon;
	String[] PlacesUrls;

	String[] Comments;
	String[] CommentsPlace;
	String[] CommentsDate;
	static Context context;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);

		context = getApplicationContext();

		new getPlace().execute();

	}

	/**
	 * 
	 * @author Monica class that extends AsyncTask to execute the communication
	 *         with the server
	 */
	class getPlace extends AsyncTask<Void, Void, String> {

		/**
		 * Called after the execute of the thread
		 */
		@Override
		protected void onPreExecute() {

		}

		/**
		 * Called if the task is canceled
		 */
		@Override
		public void onCancelled() {

		}

		/**
		 * Called after finishing
		 */
		@Override
		protected void onPostExecute(String result) {

			Log.i("In Thread", "end loading");

			// after execution the mapActivity is started
			Intent intent = new Intent().setClass(CairodioClient.this,
					CairodioMapActivity.class);
			startActivity(intent);
		}

		/**
		 * the task being executed as a thread in the back ground
		 */
		@Override
		protected String doInBackground(Void... params) {
			try {
				// Creating HTTP clients to comununicate with the server
				DefaultHttpClient CLIENT = new DefaultHttpClient();
				DefaultHttpClient CLIENT1 = new DefaultHttpClient();
				DefaultHttpClient CLIENT2 = new DefaultHttpClient();

				// The different paths for the server
				final String path = SERVER + "/getRecords";
				final String path2 = SERVER + "/getVersion";
				final String path3 = SERVER + "/getComments";

				HttpResponse resp = CLIENT.execute(new HttpGet(path));
				HttpResponse resp2 = CLIENT1.execute(new HttpGet(path2));
				HttpResponse resp3 = CLIENT2.execute(new HttpGet(path3));

				final String respStr = EntityUtils.toString(resp.getEntity());
				final String respStr2 = EntityUtils.toString(resp2.getEntity());
				final String respStr3 = EntityUtils.toString(resp3.getEntity());

				if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
						&& resp2.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

					try {

						// Saving data using JSONArrays

						JSONArray responseJson = new JSONArray(respStr);
						JSONArray responseJson2 = new JSONArray(respStr2);
						JSONArray responseJson3 = new JSONArray(respStr3);

						JSONObject ver = responseJson2
								.getJSONObject(responseJson2.length() - 1);

						// Getting the version of the server DB

						Version = ver.getDouble("number");

						CairodioDbAdapter dbAdapter = ((CairodioApplication) getApplication())
								.getAdapter();

						// Getting all the touristic places saved on the server

						PlacesNames = new String[responseJson.length()];
						PlacesLat = new double[responseJson.length()];
						PlacesLon = new double[responseJson.length()];
						PlacesUrls = new String[responseJson.length()];

						int i = 0;
						for (i = 0; i < responseJson.length(); i++) {
							JSONObject Place = responseJson.getJSONObject(i);

							PlacesNames[i] = Place.getString("name");
							PlacesLat[i] = Place.getDouble("lat");
							PlacesLon[i] = Place.getDouble("lon");
							PlacesUrls[i] = Place.getString("urls");

						}

						// Calling a method to synchronize the places on the
						// local DB with the server

						dbAdapter.SynchronizePlaces(Version, PlacesNames,
								PlacesLat, PlacesLon, PlacesUrls, Comments);

						// Getting all the comments saved on the server

						Comments = new String[responseJson3.length()];
						CommentsPlace = new String[responseJson3.length()];
						CommentsDate = new String[responseJson3.length()];

						for (i = 0; i < responseJson3.length(); i++) {
							JSONObject comment = responseJson3.getJSONObject(i);

							Comments[i] = comment.getString("comment");
							CommentsPlace[i] = comment.getString("placeName");
							CommentsDate[i] = comment.getString("date");

						}

						// Calling a method to synchronize the comments on the
						// local DB with the server

						dbAdapter.SynchronizeComments(Comments, CommentsPlace,
								CommentsDate);

					} catch (JSONException e) {
						e.printStackTrace();
						Toast.makeText(getBaseContext(), "Error parsing JSON",
								Toast.LENGTH_LONG).show();
					}
				}

				else
					Log.e("Load JSON", "Failed to download file");
			} catch (Exception e) {
				Log.e("Client", e.getMessage(), e);
			}

			return "";
		}

	}

}
